from rest_framework import serializers
from .models import Absent,AbsentType,AbsentStatusChoices
from apps.oaauth.serializers import UserSerializer
from rest_framework import exceptions
from .utils import get_responder


## 因为这里 absent 这个 model 引用了 absentType 这个外键 所以要 处理 absentType 该字段相关的完整数据结构
class AbsentTypeSerializer(serializers.ModelSerializer):
    class Meta:
        model = AbsentType
        fields = '__all__'

class AbsentSerializer(serializers.ModelSerializer):

    ## read_only 前端不传，后端值返回这个字段的值
    absent_type = AbsentTypeSerializer(read_only=True)
    ## write_only 用户提交的是 外键的ID 而不是 整个外键对象
    absent_type_id = serializers.IntegerField(write_only=True)
    ## 请求人、审批人 不让前端不用传
    requester = UserSerializer(read_only=True)
    responder = UserSerializer(read_only=True)

    def __init__(self, *args, **kwargs):
        print("开始序列化器。。。。")
        super().__init__(*args, **kwargs)

    class Meta:
        model = Absent
        fields = '__all__'

    ## 验证 absent_type_id 是否在数据库中存在
    def validate_absent_type_id(self, value):
        if not AbsentType.objects.filter(id=value).exists():
            raise exceptions.ValidationError("考勤类型不存在")
        return value

    def create(self, validated_data):
        print(f"validated_data is {validated_data}")
        request = self.context['request']
        print(f"create方法中========> request: {request}")
        user = request.user
        print(f"create方法中的 user ========> user: {user}")
        responder = get_responder(request)

        ## 董事会 免批
        if responder is None:
            print(f"修改之前的 validated_data 是： {validated_data}")
            validated_data['status'] = AbsentStatusChoices.PASS
            print(f"修改之后的 validated_data 是： {validated_data}")

        absent = Absent.objects.create(**validated_data,requester=user, responder=responder)
        return absent



    def update(self, instance, validated_data):
        print(f"update 方法中的 instance是 ：{instance}")
        if instance.status != AbsentStatusChoices.AUDITING:
            raise exceptions.APIException(detail="已经提交不可修改")
        ## 在序列化器中 获取当前登录的用户
        request = self.context.get("request")
        user = request.user
        if instance.responder.uid != user.uid:
            raise exceptions.AuthenticationFailed(detail="你不是审批人")
        instance.status =  validated_data["status"]
        instance.response_content = validated_data["response_content"]
        instance.save()
        return instance